export default {
	namespaced: true,
	state: () => ({
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	mutations: {
		addToCart(state, goods) {
			const findResult = state.cart.find(v => v.goods_id === goods.goods_id)
			if (!findResult) {
				state.cart.push(goods)
			} else {
				findResult.goods_count++
			}
			this.commit('m_cart/saveToStorage')
		},
		//改变单选框状态
		updateGoodsState(state, goods) {
			const findResult = state.cart.find(v => v.goods_id === goods.goods_id);
			if (findResult) {
				findResult.goods_state = !goods.goods_state
				this.commit('m_cart/saveToStorage')
			}
		},
		//更新商品数量
		updateGoodsNumber(state, goods) {
			const findResult = state.cart.find(v => v.goods_id === goods.goods_id);
			if (findResult) {
				findResult.goods_count = goods.goods_count
				this.commit('m_cart/saveToStorage')
			}
		},
		//删除购物车商品
		removeGoodsById(state, id) {
			state.cart = state.cart.filter(v => v.goods_id !== id)
			this.commit('m_cart/saveToStorage')
		},
		//全选反选
		updateAllGoodsState(state, newState) {
			state.cart.forEach(v => v.goods_state = newState)
			this.commit('m_cart/saveToStorage')
		},
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		}
	},
	getters: {
		//购物车所有商品的数量
		allTotal(state) {
			return state.cart.reduce((prev, next) => {
				return prev + next.goods_count
			}, 0)
		},
		//选中商品的数量
		total(state) {
			return state.cart.filter(v => v.goods_state).reduce((prev, next) => {
				return prev + next.goods_count
			}, 0)
		},
		totalPrice(state) {
			return state.cart.filter(v => v.goods_state).reduce((prev, next) => {
				return prev + next.goods_count * next.goods_price
			}, 0)
		}
	}
}
